//
//  HYDownLoadViewController.m
//  MusicMV
//
//  Created by Eternity on 16/3/23.
//  Copyright © 2016年 Eternity. All rights reserved.
//

#import "HYDownLoadViewController.h"
#import "AFHTTPRequestOperation.h"
#import "AFHTTPRequestOperationManager.h"
#import "LHYDownLoadManager.h"
#import <MediaPlayer/MediaPlayer.h>
@interface HYDownLoadViewController ()<UITableViewDelegate , UITableViewDataSource>

@property (nonatomic , strong) UIBarButtonItem *buttonLeft;

@property (nonatomic , strong) UILabel *label1;

@property (nonatomic , strong) UITableView *tableView;


@end

@implementation HYDownLoadViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
}

- (void)viewWillAppear:(BOOL)animated {

    NSMutableArray *arr = [self getArr];
    if (arr.count == 0) {
        _label1.text = @"抱歉您还没有下载过MV,赶快下载吧";
        _label1.backgroundColor = [UIColor clearColor];
        _label1.textColor = [UIColor lightGrayColor];
        _tableView.alpha = 0;

    } else {
        _label1.alpha = 0;
        _tableView.alpha = 1;
    
    }
    
}

// 从本地获取下载的数组
- (NSMutableArray *)getArr {
    
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", pathArr);
    NSString *documentPath = [pathArr lastObject];
    NSString *arrPath = [documentPath stringByAppendingPathComponent:@"arrPath.list"];
    
    NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];
    NSMutableArray *arrM = [NSMutableArray arrayWithArray:arr];
    
    return arrM;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的下载";
    self.buttonLeft = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"goBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]style:(UIBarButtonItemStylePlain) target:self action:@selector(buttonLeft:)];
    self.view.backgroundColor = [UIColor whiteColor];
            self.label1 = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH / 2 - 150 * wt, SCREEN_WIDTH / 2 , 300 * wt, 50)];
    [self.view addSubview:_label1];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEIGHT - 64) style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[HYDownLoadTableViewCell class] forCellReuseIdentifier:@"HYDownLoadTableViewCell"];
    
    self.buttonLeft = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"goBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ]style:(UIBarButtonItemStylePlain) target:self action:@selector(buttonLeft:)];
    self.navigationItem.leftBarButtonItem = _buttonLeft;
    UIImage *image1 = [[UIImage imageNamed:@"SHANCHU"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:image1 style:(UIBarButtonItemStylePlain) target:self action:@selector(rightButton:)];
  
    self.navigationItem.rightBarButtonItem = rightButton;
    
}

- (void)rightButton:(UIBarButtonItem *)button {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否删除全部下载" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        NSFileManager *manager = [NSFileManager defaultManager];

        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSLog(@"%@", pathArr);
        NSString *documentPath = [pathArr lastObject];
        NSString *arrPath = [documentPath stringByAppendingPathComponent:@"arrPath.list"];
        [manager removeItemAtPath:arrPath error:nil];
        NSString *catchPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)  lastObject] stringByAppendingString:[NSString stringWithFormat:@"/HSCache/Download/Video"]];
        NSLog(@"%@",catchPath);
        [manager removeItemAtPath:catchPath error:nil];
        [_tableView reloadData];
        _label1.text = @"抱歉您还没有下载过MV,赶快下载吧";
        _label1.backgroundColor = [UIColor clearColor];
        _label1.textColor = [UIColor lightGrayColor];
        _label1.alpha = 1;
        _tableView.alpha = 0;
        

        
        
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action];
    [alert addAction:action1];
[self presentViewController:alert animated:YES completion:nil];
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    
    
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
    
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSFileManager *manager = [NSFileManager defaultManager];

        NSMutableArray *arrayModel = [self getArr];
        NSString *catchPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)  lastObject] stringByAppendingString:[NSString stringWithFormat:@"/HSCache/Download/Video/%lu.mp4",(unsigned long)[        arrayModel[indexPath.row][@"filePath"] hash]]];
        [manager removeItemAtPath:catchPath error:nil];
        [arrayModel removeObjectAtIndex:indexPath.row];
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSLog(@"%@", pathArr);
        NSString *documentPath = [pathArr lastObject];
        NSString *arrPath = [documentPath stringByAppendingPathComponent:@"arrPath.list"];
        
        [arrayModel writeToFile:arrPath atomically:YES];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [_tableView reloadData];

        _label1.text = @"抱歉您还没有下载过MV,赶快下载吧";
        _label1.backgroundColor = [UIColor clearColor];
        _label1.textColor = [UIColor lightGrayColor];
        
        if (arrayModel.count) {
            _tableView.alpha = 1;
            _label1.alpha = 0;
        } else {
            _tableView.alpha = 0;
            _label1.alpha = 1;
        }
        

        
        
    }
    
    
    
}





- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSMutableArray *arr = [self getArr];
    return arr.count;


}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HYDownLoadTableViewCell *hyDown = [tableView dequeueReusableCellWithIdentifier:@"HYDownLoadTableViewCell" forIndexPath:indexPath];
    if (indexPath.row % 2 != 0 ) {
        
        hyDown.backgroundColor = RGBA(0,350, 130, 1);
        
    }

    NSMutableArray *adic = [self getArr];
    NSMutableArray *arr = [HYDownLoadModel modelWithArray:adic];
    HYDownLoadModel * model = arr[indexPath.row];
    hyDown.downModel = model;
    return hyDown;

    

}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100 * ht;


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    NSMutableArray *adic = [self getArr];
    NSMutableArray *arr = [HYDownLoadModel modelWithArray:adic];
    HYDownLoadModel * model = arr[indexPath.row];

    NSString *catchPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)  lastObject] stringByAppendingString:[NSString stringWithFormat:@"/HSCache/Download/Video/%lu.mp4",(unsigned long)[model.filePath hash]]];
        MPMoviePlayerViewController *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:catchPath]];
    NSLog(@"%@",model.filePath);
        [self presentViewController:moviePlayer animated:YES completion:nil];



}



- (void)buttonLeft:(UIBarButtonItem *)button {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = RGBA(38,38, 38, 1);
    
    self.navigationController.navigationBar.alpha = 1;
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
